﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Areas.Bots.Models;
using Services;
using DAL;

namespace WebUI.Areas.Bots.Controllers
{
    public partial class ScheduleController : BaseController
    {
        #region  Member Vairables

        readonly IBotService _botService;

        #endregion

        #region Constructor

        public ScheduleController(ISessionHelper sessionHelper, IBotService botService)
            : base(sessionHelper)
        {
            this._botService = botService;
        }

        #endregion

        #region Action Methods

        public virtual ViewResult Index()
        {
            Schedule schedule = new Schedule
            {
                RecurringValue = _sessionHelper.Bot.RecurringValue,
                RecurringSpan = _sessionHelper.Bot.RecurringSpan,

                StartPeriod = _sessionHelper.Bot.StartPeriod,
                StartPeriodHour = _sessionHelper.Bot.StartPeriod.HasValue ? _sessionHelper.Bot.StartPeriod.Value.Hour : (int?)null,

                EndPeriod = _sessionHelper.Bot.EndPeriod,
                EndPeriodHour = _sessionHelper.Bot.EndPeriod.HasValue ? _sessionHelper.Bot.EndPeriod.Value.Hour : (int?)null
            };

            return View(schedule);
        }

        [HttpPost]
        public virtual ActionResult Save(Schedule schedule)
        {
            if (ModelState.IsValid)
            {
                _sessionHelper.Bot.RecurringValue = schedule.RecurringValue;
                _sessionHelper.Bot.RecurringSpan = schedule.RecurringSpan;
                _sessionHelper.Bot.StartPeriod = new DateTime(schedule.StartPeriod.Value.Year, schedule.StartPeriod.Value.Month, schedule.StartPeriod.Value.Day, schedule.StartPeriodHour.Value, 0, 0);
                _sessionHelper.Bot.EndPeriod = schedule.EndPeriod;

                IDictionary<string, string> validationDictionary = _botService.ValidateScheduleStep(_sessionHelper.Bot, schedule.EndPeriodHour);

                foreach (var entry in validationDictionary.Values)
                {
                    ModelState.AddModelError(string.Empty, entry);
                }

                if (ModelState.IsValid)
                {
                    if (_sessionHelper.Bot.EndPeriod.HasValue)
                    {
                        _sessionHelper.Bot.EndPeriod = new DateTime(schedule.EndPeriod.Value.Year, schedule.EndPeriod.Value.Month, schedule.EndPeriod.Value.Day, schedule.EndPeriodHour.Value, 0, 0);
                    }

                    return RedirectToRoute(new { action = MVC.Bots.BotFilters.ActionNames.Index, controller = MVC.Bots.BotFilters.Name, step = MVC.Bots.BotFilters.Name });
                }
            }

            return View(MVC.Bots.Schedule.Views.Index, schedule);
        }

        #endregion
    }
}